# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module WelcomeHelper

  include ProjectsHelper

  def welcome_join_in_course(project, user)
    if(user.logged? && 
        !(course_endTime_timeout? project) && 
        (project.course_extra.teacher.id != user.id)
      )
      join_in_course(project, user)
    end
  end

  def get_course_avatar project
    if get_avatar?(project)
      url_to_avatar(project)
    else 
      '../images/avatars/Project/course.jpg'
    end 
  end

  def get_project_avatar project
    if get_avatar?(project)
      url_to_avatar(project)
    else 
      '../images/avatars/Project/0'
    end 
  end
  # 前略·天国の首页君/Earth has been unable stop to welcomePage's.
  # sum      - 要搜索的项目数量
  # max_rate - 新项目所占所有项目的比重，10分制
  #
  # Examples
  #   
  #   find_miracle_course(10, 7)
  #   # => 前7个项目为新课程，后面三个是参与人数最多的
  #
  # Returns project&courses array
  def find_miracle_course(sum=10, max_rate=7, school_id)
    
    if User.current.user_extensions.school.nil? and school_id.nil?
      Project.active.visible.course_entities.
        joins(:course_extra).
        joins(:memberships).
        group('members.project_id').
        reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum
#    elseif school_id.nil?

    else
      if school_id.nil?
       Project.active.visible.course_entities.
          joins(:course_extra).
          joins(:memberships).
          where("#{Course.table_name}.school_id = ?", User.current.user_extensions.school.id).
          group('members.project_id').
          reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum
      else 
        if school_id == "0"
          Project.active.visible.course_entities.
            joins(:course_extra).
            joins(:memberships).
            group('members.project_id').
            reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum          
        else
        Project.active.visible.course_entities.
            joins(:course_extra).
            joins(:memberships).
            where("#{Course.table_name}.school_id = ?", school_id).
            group('members.project_id').
            reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum      
        end 
      end 
    end   
#    else
#      Project.active.visible.course_entities.
#        joins(:course_extra).
#        joins(:memberships).
#        where("#{Course.table_name}.school_id = ?", school_id).
#        group('members.project_id').
#        reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum        
#    end 
    # max = sum*(max_rate.to_f/10)
    # c1 = find_new_course(sum).to_a.dup
    # c2 = find_all_hot_course(sum).to_a.dup
    # c2 = c2 - c1
    # (c1.take(max)+c2).take(sum)
  end

  #查找所有学校按每个学校开设课程数量降序排序
  #page 分页查询开始条数的编号,从0开始
  #limit 分页查询的数量
  def find_maxmin_course_school page,limit
    School.find_by_sql("SELECT *,(SELECT COUNT(*) FROM courses WHERE school_id = schools.id) AS a
      FROM schools
      ORDER BY a DESC LIMIT #{page},#{limit}")
    #School.where(" id IN (SELECT school_id FROM courses GROUP BY school_id)").limit limit;
    #School.order("#{School.course_count}").limit(limit).all
    #@school = School.all.sort
    #@school.each do |s|
    #  s.courses.count
    #end
    #result = []
    #@school = School.all.to_ary
    #i = 1
    #for i in  i < School.count
    #  j = i - 1
    #  for j in j > 0
    #    if @school[j].courses.count >
    #  end
    #end
  end

  def find_miracle_project(sum, max_rate)
    max = sum*(max_rate.to_f/10)
    c1 = find_new_project(sum).to_a.dup
    c2 = find_all_hot_project(sum).to_a.dup
    (c2.take(sum-max)+c1.take(max)).take(sum)
  end
  
  def find_new_course limit=15
    Project.visible.joins(:course_extra).where("#{Project.table_name}.project_type = ? ", 1).order("courses.time DESC, #{Project.table_name}.created_on DESC").limit(limit).all
  end
  
  def find_new_project limit=15
    Project.visible.where("#{Project.table_name}.project_type = ? ", 0).order("#{Project.table_name}.updated_on DESC, #{Project.table_name}.created_on DESC").limit(limit).all
  end


  def find_all_hot_project limit=15
    sort_project_by_hot limit
  end

  def find_all_hot_course limit=15
    sort_course_by_hot limit
  end

  def find_all_new_hot_course limit = 9 ,school_id = 0
    #sort_project_by_hot_rails 1, 'course_ac_para DESC', limit
    time_now = Time.new.strftime("%Y");
    Project.visible.joins(:project_status).where("#{Project.table_name}.project_type = ? and #{Project.table_name}.created_on like '%#{time_now}%' and #{Project.table_name}.identifier not in
      (select extra from courses where school_id = ?)", 1,school_id).order("course_ac_para DESC").limit(limit).all
  end

  def find_all_hot_bid
    sort_bid_by_hot
  end

  def find_all_hot_contest limit=10
    Contest.reorder("created_on DESC").all.take limit
    # mix_bid = []
    # mix_bid += Contest.reorder("created_on DESC").take(limit).to_a
    # mix_bid += Bid.visible.where('reward_type = ?', 2).reorder('bids.created_on desc').take(limit).to_a
    # mix_bid.sort do |older, newer|
      # newer.created_on - older.created_on
    # end
    # mix_bid.take limit
  end

  def find_all_hot_softapplication limit=10
    Softapplication.reorder("created_at DESC").all.take limit
  end  

  def cal_memos_count event
    return nil if event.parent_id
    event.replies_count
  rescue NoMethodError
    nil
  end
  
  def topic_last_time topic
    return topic.event_datetime if ( !(topic.methods.to_s =~ %r[last_reply]) || topic.last_reply.nil? )
    topic.last_reply.event_datetime
  end
  

  def time_tag_welcome time
    text = distance_of_time_in_words(Time.now, time)
    content_tag('span', text, :title => format_time(time))
  end

  def show_grade project
    grade = 0
    begin
      grade = project.project_status.grade if project && project.project_status
    rescue Exception => e
      logger.error "Logger.Error [WelcomeHelper] ===> #{e}"
    end
     "项目评分：".html_safe << grade.to_s
  end
  
  def show_user_content event
    str = '&nbsp;'.html_safe
    case event.event_type
    when 'news'
      str << content_tag("span", "发表了") << 
        content_tag("span", find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << 
        link_to(truncate(strip_tags(event.event_description).gsub(/&nbsp;/,''), length: 30, omission:'...'), event.event_url)
    when 'issue', 'message' , 'bid' , 'wiki-page' , 'document'
      str << content_tag("span", "发表了") <<
             content_tag("span", find_all_event_type(event)) << 
             ':&nbsp;'.html_safe << 
             link_to(truncate(event.event_title, length: 30, omission:'...'), event.event_url)
    when 'reply' ,'Reply', 'Memo'
      str << content_tag("span", "发表了") << 
        content_tag("span", find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << 
        link_to(truncate(strip_tags(event.event_description).gsub(/&nbsp;/,''), length: 30, omission:'...'), event.event_url)
    else
      str << content_tag("span", "更新了") << 
        content_tag("span", find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << link_to(truncate(event.event_title, length: 30, omission:'...'), event.event_url)
    end
    str
  rescue Exception => e
    str << content_tag("span", '未知内容')
  end
  
  def show_event_reply event
    str = "回复("
    case event.event_type
    when 'news'
      str << link_to( event.comments.count, news_path(event)) << ")"
    when "issue"
      str << link_to(cal_issues_count(event), issue_path(event)) << ")"
    when "Memo"
      str << link_to(cal_memos_count(event), forum_memo_path(event.forum_id,event.id)) << ")"
    else
      str = ""
    end
    str.html_safe
  end

  def find_new_forum_topics limit=7
    # Memo.where('memos.parent_id IS NULL').reorder('memos.created_at DESC').limit(limit)
    # activity = Redmine::Activity::Fetcher.new(nil)
    # activity.scope=['memos']
    # activity.events_welcome(nil, nil, {:limit => limit})

    resultSet = Memo.includes(:last_reply).order('COALESCE (last_replies_memos.created_at, memos.created_at) DESC').limit(limit)
    # resultSet += Message.where('messages.parent_id IS NULL').includes(:last_reply).order('COALESCE (last_replies_messages.created_on, messages.created_on) DESC').limit(limit)
    
    # resultSet = Memo.includes(:children).where('parent_id IS NULL').order('updated_at DESC').limit(limit)
    # resultSet += Message.includes(:children).where('parent_id IS NULL').order('updated_on DESC').limit(limit)
    # resultSet.sort! {|x,y| y.event_datetime <=> x.event_datetime}
    # resultSet = resultSet.to_a
    # for i in 0..(resultSet.size-1)
      # resultSet[i] = resultSet[i].children.last if resultSet[i].children.count > 0
    # end
    # resultSet.take(limit)
  end

  private

  def sort_project_by_hot limit=15
    sort_project_by_hot_rails 0, 'grade DESC', limit
  end

  def sort_course_by_hot limit=15
    sort_project_by_hot_rails 1, 'course_ac_para DESC', limit
  end

  def sort_bid_by_hot
    sort_bid_by_hot_rails 1
  end

  def sort_contest_by_hot
    sort_bid_by_hot_rails 2
  end
#new added by linchun  
  def sort_contest_by_time 
    sort_bid_by_time 2
  end

  #取得论坛数据
  def find_hot_forum_topics limit=9
    ## 以下语句会内链接自身查询出最后一条回复时间，没有回复的帖子不会显示
    # Memo.find_by_sql("
    #   SELECT memos.*, reply.created_at AS last_reply_date FROM memos AS memos 
    #     INNER JOIN memos
    #     AS reply ON memos.last_reply_id=reply.id
    #   WHERE memos.parent_id IS NULL
    #   ORDER BY memos.replies_count DESC, memos.created_at DESC
    #   LIMIT #{limit}")

    #Memo.order('replies_count DESC').where('replies_count <> 0').limit(limit)
    
    resultSet = Memo.order('replies_count DESC, created_at DESC').limit(limit)
    resultSet += Message.order('replies_count DESC, created_on DESC').limit(limit)
    resultSet.sort! {|x,y| (y.replies_count <=> x.replies_count).nonzero? || (y.event_datetime <=> x.event_datetime)}
    resultSet.take(limit)
  end

  def sort_project_by_hot_rails project_type=0, order_by='grade DESC', limit=15
    # Project.find_by_sql("
			# SELECT p.id, p.name, p.description, p.identifier, t.project_id
			# FROM projects AS p LEFT OUTER JOIN (
				# SELECT project_id,grade FROM project_statuses
				# WHERE project_type = #{project_type} ORDER BY #{order_by} LIMIT #{limit} ) AS t ON p.id = t.project_id ")
    Project.visible.joins(:project_status).where("#{Project.table_name}.project_type = ?", project_type).order(order_by).limit(limit).all
  end

  def sort_bid_by_hot_rails reward_type, limit = 10
    Bid.visible.where('reward_type = ?', reward_type).reorder('bids.commit desc').limit(limit)
  end
  
  def sort_bid_by_time reward_type, limit = 10
    Bid.visible.where('reward_type = ?', reward_type).reorder('bids.created_on desc').limit(limit)
  end
  
  def find_all_event_type event
    case event.event_type
    when 'news'
      '新闻'
    when 'issue'
      '缺陷'
    when 'message'
      '主题'
    when 'Reply','reply'
      '回复'
    when 'bid'
      '作业'
    when 'Memo'
      '主题'
    when 'document'
      '文件'
    when 'changeset'
      '版本库'
    when 'issue-note'
      '问题说明'
    else
    event.event_type
    end
  end
  
  def newbie_send_path
    create_new_forum_path '新手讨论'
  end
  def suggestion_send_path
    create_new_forum_path '网站建议'
  end

  private

  def create_new_forum_path name
    # 没有论坛则返回'#' 不能发帖
    # 否则到指定论坛里发帖
    # 没有找到置顶论坛就跑默认第一个论坛发帖
    forum_relation = create_find_undefine_forum name
    backUrl = '#'
    backUrl = new_forum_memo_path(Forum.first) if Forum.count > 0
    backUrl = new_forum_memo_path(forum_relation.first) if !forum_relation.empty?
    return backUrl
  end
  def create_find_undefine_forum name
    Forum.where("name LIKE \'%#{name}%\'")
  end
end
